# _*_ coding: utf-8 _*_
__author__ = 'yinlei'
__date__ = '2018-05-18 8:23'

from flask import Blueprint,make_response,request
from utils import digital
from utils.alidayu import send_sms
from utils.captcha import Captcha
from utils import restful
from apps.common.forms import SMSCaptchaForm
import json
from io import BytesIO
import re
from utils import zlcache

common_route = Blueprint('common', __name__, url_prefix='/common')


@common_route.route('/')
def index():
    return 'common index'
@common_route.route('/captcha')
def graph_captcha():
    # 获取验证码
    text, image = Captcha.gene_graph_captcha()
    out = BytesIO()
    image.save(out, 'png')
    out.seek(0)
    resp = make_response(out.read())
    resp.content_type = 'image/png'
    zlcache.set(text.lower(),text.lower(),60*2)
    return resp


@common_route.route('/sms_captcha',methods=['POST',])
def sms_captcha():
    form = SMSCaptchaForm(request.form)

    if form.validate():
        telephone = form.telephone.data
        code = digital.get_random_digital(6)
        params = json.dumps({'code': code})
        status_code, message = send_sms(telephone, params)
        if status_code == 'OK':
            zlcache.set(telephone,code)
            return restful.success('短信验证码发送成功')
        else:
            return restful.params_error('短信验证码发送失败{}'.format(message))
    else:
        return restful.params_error('参数错误')

